from django.views import View
from io import BytesIO
from PIL import Image
from random import choices
from captcha.image import ImageCaptcha
from django.http import HttpResponse


class CaptchaView(View):
    def get(self, request):
        code, image = CaptchaView.get_captcha()
        out = BytesIO()
        request.session["code"] = code
        image.save(out, 'png')
        image.save(out, 'PNG')
        return HttpResponse(out.getvalue())

    @staticmethod
    def get_captcha(content='0123456789'):
        """ 生成验证码 """
        image = ImageCaptcha()
        # 获取字符串
        captcha_text = "".join(choices(content, k=4))
        # 生成图像
        captcha_image = Image.open(image.generate(captcha_text))
        return captcha_text, captcha_image
